package com.byx.chatserver.service.impl;

import com.byx.chatserver.entity.MailType;
import com.byx.chatserver.entity.VerifyEmailParam;
import com.byx.chatserver.service.IMailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * MailServiceImpl
 * 封装邮件操作
 * @author Superb
 * @date 2021/3/22 17:54
 */
@Service
public class MailServiceImpl implements IMailService {
    private static final int EFFECTIVE_TIME = 300;
    @Resource
    private JavaMailSender mailSender;

    @Resource
    private SpringTemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void send(String to, String subject, String content, MailType mailType) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;

        Context context = new Context();
        VerifyEmailParam verifyEmailParam = new VerifyEmailParam();
        verifyEmailParam.setUserEmail(to);
        verifyEmailParam.setOperate(mailType.getTypeName());
        verifyEmailParam.setVerificationCode(content);
        verifyEmailParam.setEffectiveTime(EFFECTIVE_TIME/60+"分钟");
        context.setVariable("verifyEmailParam", verifyEmailParam);
        String emailContent = templateEngine.process("default_verify_mail", context);

        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(emailContent, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }
}
